//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  name: "",
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    return {
      chatStrId: "",
      coursesId: "", //	课程id
      expiraTime: "", //过期时间
      chatId: "", //群id
      shareId:"", //分享ID
      watchSecond: 0,
      errorShow: false, //失败弹窗
      succeesShow: false,
      videoFlag: false,
      hasFinish: false, //是否看完
      efficacyType: 1,
      answerType: 1,
      goodsUrl: "",
      courses: {},
      answerIndex: -1,
      watchRecordId: "", //观看记录Id
      optionsId: "", //选项ID
      timer: 0,
      timingTime: 1,
      awserObj: {},
      errorMsg: "",
      durationTime: "", //显示的时间
      duration: "", //总秒数
      description: "", //详情
      textDescription:"",
      descMsg: "",
      coursesErrorType: 0,
      presentTime: "", //获取本地时间
      timeFlag:false, //显示倒计时
      playbackFlag:false,
      liveFlag:false
      //直播观看时间

    };
  },
  //监听属性 类似于data概念
  computed: {
    beforeDay() {
      return function(time) {
        let endTime = time * 1000;
        if (!Number(time)) return;
        if(time === 0){
          this.timeFlag = false;
          this.videoFlag = true;
        }
        return endTime - Number(this.presentTime);
      }
    },
    backDay() {
      if(this.courses.back_time_start && this.courses.back_time_end) {
        if(this.presentTime > (this.courses.back_time_start * 1000) && this.presentTime < (this.courses.back_time_end * 1000)) {
          return true;
        }  else {
          return false;
        }
      }
    },
    liveDay() {
      if(this.courses.live_time_start && this.courses.live_time_end && this.courses.courses_type == 1) {
        if(this.presentTime > (this.courses.live_time_start * 1000) && this.presentTime < (this.courses.live_time_end * 1000)) {
          return true;
        }  else {
          return false;
        }
      }
    }
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    //回放时间记录
    onPlayerPlay(event) {
      event.currentTime = this.currentTime;
      this.videoFlag = false;
    },
    onPlayer(event) {
      event.preventDefault();
    },
    onPlayerEnded(event) {
      this.videoFlag = true;
      this.hasFinish = true;
      this.timingTime = 1;
      this.coursesWatch();
      this.shortVideo();
    },
    shortVideo() {
      this.hasFinish = false;
      if(this.$refs.goodsVideo.duration <= this.duration && this.courses?.carousel) {
        this.$refs.goodsVideo.currentTime = 0;
        this.timingTime = 1;
        this.watchRecordId = 0;
        this.$refs.goodsVideo.play();
      }
      if(!this.liveDay  && !this.courses?.carousel) {
        this.$refs.goodsVideo.pause();
      }
      if(this.liveDay) { //如果直播看完
        
        // this.watchRecordId = 0;
        this.$refs.goodsVideo.play();
        let liveTimeSum = this.courses?.live_time_end -this.courses?.live_time_start; //直播总时长
        if(Math.floor(this.$refs.goodsVideo.duration) >= liveTimeSum ) {
          this.$refs.goodsVideo.pause();
          this.coursesDetail();
        }
      }
      let presentTime = new Date().getTime();
      if(presentTime >= (this.courses.live_time_end * 1000) && this.liveDay) { //大于直播时间，刷新页面
        this.$router.go(0)
      }
      if(presentTime >= (this.courses.back_time_end * 1000) && this.backDay) { //大于回放时间，刷新页面
        this.$router.go(0)
      }
      
    },
    onLoadedmetadata(event) {
      let duration = Math.floor(this.$refs.goodsVideo.duration);
      if(!this.backDay && !this.courses?.carousel) {
        this.duration = duration;
      }
      this.liveDayFun(duration);
    },
    liveDayFun(duration) {
      if(this.liveDay) { //直播时间
        this.watchRecordId = 0;
        let liveTime = (this.presentTime / 1000) - this.courses?.live_time_start;
        this.$nextTick(() => {
          if(this.courses?.carousel) { //如果有轮播时间处理直播功能
            liveTime >= this.duration?this.$refs.goodsVideo.currentTime = Math.floor(liveTime % this.duration):this.$refs.goodsVideo.currentTime = liveTime;
          } else {
            //计算播放后时间除以视频时间取余
            liveTime >= this.$refs.goodsVideo.duration?this.$refs.goodsVideo.currentTime = Math.floor(liveTime % this.$refs.goodsVideo.duration):this.$refs.goodsVideo.currentTime = liveTime;
          }
          this.timingTime = this.$refs.goodsVideo.currentTime;
          this.$refs.goodsVideo.play();
        })
      }
    },
    computingTime(afterTime, backTime) {
      if(backTime === 0) {
        this.videoFlag = true;
      }
      if (!Number(backTime)) return;
      let res = Number(afterTime) - Number(backTime);
      if (res >= 0) {
        this.timeFlag = true;
      } else {
        this.timeFlag = false;
        this.videoFlag = true;
      }
    },
    videoPay() {
      this.videoFlag = false;
      this.has_finish = false;
      this.$nextTick(() => {
        setTimeout(() => {
          this.$refs.goodsVideo.play();
        },500)
      })
    },
    answerClick(index) {
      this.answerType = index;
    },
    topicOn(id, index) {
      this.optionsId = id;
      this.answerIndex = index;
    },
    resetClick() {
      this.answerIndex = -1;
      this.errorShow = false;
      this.optionsId = "";
    },
    sucClick() {
      this.succeesShow = false;
      this.coursesWatch();
    },
    coursesDetail() {
      let query = {
        courses_id: Number(this.coursesId),
        chat_id: Number(this.chatId),
        share_id:Number(this.shareId),
        expira_time: this.expiraTime
      };
      if (this.fun.getKey("client") === "work" || window.localStorage.getItem("client")) {
        query = { ...this.getConfig, ...query, chat_str_id: this.chatStrId };
      }
      $http
        .post("plugin.wechat-video-courses.frontend.controller.member.courses.courses-index", query, "loading")
        .then(res => {
          if (res.result === 1) {
            let data = res.data;
            this.courses = data.courses;
            this.description = this.courses?.introduce?.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"');
            this.textDescription = this.courses?.lecturer_introduce?.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"');
            let options = this.courses?.topic?.options;
            if(options && options.length > 0) {
              this.awserObj = options.find(item => item.has_answer == 1);
            }
            this.currentTime = data.courses?.not_finish_watch?.duration;
            if(this.courses?.not_finish_watch && this.courses?.courses_type == 1 && this.backDay) { //回放时间功能，获取播放过的视频时间秒数
              this.timingTime = this.courses?.not_finish_watch?.duration || 1;
              this.$refs.goodsVideo.currentTime = this.courses?.not_finish_watch?.duration || 1;
              localStorage.setItem('backFlag', true);
            }
            if(this.courses?.not_finish_watch && this.courses?.courses_type == 1 && this.liveDay) {
              localStorage.setItem('liveFlag', true);
            }
            
            if(this.courses?.carousel) { // 获取轮播时间
              this.duration = Number(this.courses?.carousel) * 60;
            }
            
            this.computingTime(this.courses?.limit_time *1000,this.presentTime);
          } else {
            this.coursesErrorType = res?.data?.courses_error_type;
            if (!this.coursesErrorType) {
              this.$dialog.alert({
                message: res.msg
              });
            } else {
              this.descMsg = res.msg;
            }
            // this.$toast(res.msg);
          }
        })
        .catch(err => {
          console.log("getUserData::err", err);
        });
    },
    coursesWatch() {
      let duration = Math.floor(this.$refs.goodsVideo.duration);
      let query = {
        courses_id: Number(this.coursesId),
        chat_id: Number(this.chatId),
        watch_second: this.watchSecond,
        watch_record_id: Number(this.watchRecordId),
        has_finish: this.hasFinish,
        total_second:duration
      };
      if (this.fun.getKey("client") === "work" || window.localStorage.getItem("client")) {
        query = { ...this.getConfig, ...query, chat_str_id: this.chatStrId };
      }
      $http
        .post("plugin.wechat-video-courses.frontend.controller.member.courses.watch", query)
        .then(res => {
          if (res.result === 1) {
            let data = res.data;
            this.watchRecordId = data.watch_record.id;
            if(this.watchSecond >=duration) {
              this.watchRecordId = 0;
            };
            //&& this.watchSecond >= (this.courses?.reward_watch_min * 60)
            if(data.is_get_reward) {
              this.succeesShow = true;
            }
            let liveFlag = localStorage.getItem('liveFlag');
            let backFlag = localStorage.getItem('backFlag');
            let presentTime = new Date().getTime();
            if(liveFlag && presentTime >= (this.courses.live_time_end * 1000)) {
              this.$router.go(0)
              localStorage.removeItem("liveFlag");
            }
            if(backFlag && presentTime >= (this.courses.back_time_end * 1000)) {
              this.$router.go(0)
              localStorage.removeItem("backFlag");
            }
          } else {
            this.errorMsg = res.msg;
            this.errorShow = true;
          }
        })
        .catch(err => {
          // this.$toast(err);
          console.log("getUserData::err", err);
        });
    },
    tipicConfrim() {
      if (!this.optionsId && this.courses.reward_type == 0) {
        this.$toast("请选择题目");
        return;
      }
      this.coursesReply();
    },
    coursesReply() {
      let query = {
        courses_id: Number(this.coursesId),
        chat_id: Number(this.chatId),
        watch_record_id: Number(this.watchRecordId),
        options_id: this.optionsId
      };
      if (this.fun.getKey("client") === "work") {
        query = { ...this.getConfig, ...query, chat_str_id: this.chatStrId };
      }
      $http
        .post("plugin.wechat-video-courses.frontend.controller.member.courses.reply", query, "loading")
        .then(res => {
          if (res.result === 1) {
            let data = res.data;
            this.watchRecordId = data.watch_record_id;
            if(this.courses.reward_status) {
              this.succeesShow = true;
            }
          } else {
            this.errorMsg = res.msg;
            this.errorShow = true;
          }
        })
        .catch(err => {
          console.log("getUserData::err", err);
        });
    },
    onTimeupdate(event) {
      let currentTime = this.$refs.goodsVideo.currentTime;
      this.watchSecond = parseInt(currentTime);
      if (parseInt(currentTime) + 1 >= this.timingTime && this.$refs.goodsVideo.duration) {
        this.timingTime += 5;
        this.coursesWatch();
      }
      //回放时间开启轮播
      if(this.courses?.carousel) {
        if(this.$refs.goodsVideo.currentTime >= this.duration) {
          this.$refs.goodsVideo.currentTime = 0;
          this.timingTime = 1;
        }
      }
      
      
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {
    if (this.fun.getKey("client") === "work" || window.localStorage.getItem("client")) {
      this.chatStrId = window.localStorage.getItem("chat_id") || "";
    }
    this.presentTime = new Date().getTime();
    if (this.$route.query.courses_id || this.$route.query.chat_id) {
      this.coursesId = this.$route.query.courses_id;
      this.chatId = this.$route.query.chat_id;
      this.shareId = this.$route.query.share_id;
      // this.chatId = 'wrDesSDgAAtc0LSeSi5b3sZHrQQ3tocQ';//测试用
      this.expiraTime = this.$route.query.expira_time;
      this.coursesDetail();
    }
  } //如果页面有keep-alive缓存功能，这个函数会触发
};
